import base from './base.js'
import { wxlogin } from './api.js'
import cos from './upload'

let timer = ''
const urlFromat = (url) => {
  return `${base.baseUrl}${url}`
}
const setBody = (data) => {
  return Object.assign({}, data, {
    token: wx.getStorageSync('token')
  })
}

const _handleError = (res) => {
  let status = res.statusCode || -1
  if (status === 404) {
    if (res.data.code) {
      return res.data
    } else {
      return {
        msg: res.data.error
      } // 框架没启动起来错误信息字段是error
    }
  } else if(res.data.code == 401) {
    wx.hideLoading()
    // wx.showToast({
    //   title: '身份认证过期，请登陆',
    //   icon: 'none'
    // })
    // wx.clearStorage()
    // setTimeout(() => {
    //   wx.reLaunch({
    //     url: '/pages/center/center'
    //   })
    // }, 2000);
    clearTimeout(timer)
    timer = setTimeout(() => {
      wx.getUserInfo({
        success: function(e) {
          wx.login({
            success(res) {
              if (res.code) {
                const params = {
                  code: res.code,
                  userInfo: e.userInfo,
                  encryptedData: e.encryptedData,
                  iv: e.iv
                }
                wxlogin(params).then((data) => {
                  if (data.code === 200) {
                    wx.setStorageSync('token', data.token)
                  }
                })
              } else {
                console.log('登录失败！')
              }
            }
          })
        }
      })
    }, 500);
    return '授权token失效'
  } else if (res.data.code == 500 || res.data.code == 400 || res.data.code == 402 || res.data.code == 201 ) {
    return res.data
  } else {
    let data = {
      msg: '网络有点慢，请刷新后再试～'
    }
    return data
  }
}

const _fnSuccess = (res, resolved, rejected) => {
  if (res.data.code === 200) {
    wx.hideLoading()
    resolved(res.data)
  } else {
    let errorMsg = _handleError(res)
    wx.showToast({
      title: errorMsg.msg,
      icon: 'none'
    })
    rejected(errorMsg)
  }
}

const _fnFail = (res, rejected) => {
  wx.showToast({
    title: _handleError(res).msg,
    icon: 'none'
  })
  rejected(res.data)
}

const get = (url, data) => {
  data = setBody(data)
  wx.showLoading({
    title: '',
    mask: true
  });

  return new Promise((resolved, rejected) => {
    const optionsObj = {
      url: urlFromat(url),
      method: 'GET',
      data: data,
      success: (res) => {
        _fnSuccess(res, resolved, rejected)
      },
      fail: (res) => {
        _fnFail(res, rejected)
      }
    }

    wx.request(optionsObj)
  })
}

const post = (url, data, showLoading = true) => {
  data = setBody(data)
  if(showLoading) {
    wx.showLoading({
      title: '',
      mask: true
    });
  }

  return new Promise((resolved, rejected) => {
    const optionsObj = {
      url: urlFromat(url),
      method: 'POST',
      data: data,
      success: (res) => {
        _fnSuccess(res, resolved, rejected)
      },
      fail: (res) => {
        _fnFail(res, rejected)
      }
    }

    wx.request(optionsObj)
  })
}

const request = (url, data, method = 'POST') => {
  const params = setBody(data)
  return new Promise((resolved, rejected) => {
    const optionsObj = {
      url: urlFromat(url),
      method: method,
      data: params,
      success: (res) => {
        if(res.statusCode === 200) {
          if(res.data.code === 401) {
            return wx.getUserInfo({
              success: (e) => {
                wx.login({
                  success: (res) => {
                    if (res.code) {
                      request('/api/miniapp/wxlogin', {
                        code: res.code,
                        encryptedData: e.encryptedData,
                        iv: e.iv
                      }, 'POST').then((data) => {
                        if (data.code === 200) {
                          wx.setStorageSync('token', data.token)
                          console.log(url, data, method)
                          request(url, data, method).then((res) => {
                            resolved(res)
                          })
                        }
                      })
                    } else {
                      rejected(res)
                    }
                  }
                })
              }
            })
          } else {
            resolved(res.data)
          }
        } else {
          rejected(res)
        }

      },
      fail: (res) => {
        rejected(res)
      }
    }

    wx.request(optionsObj)
  })
}

const remove = (url) => {
  data = setBody(data)
  wx.showLoading({
    title: '',
    mask: true
  });

  return new Promise((resolved, rejected) => {
    const optionsObj = {
      url: urlFromat(url),
      method: 'DELETE',
      success: (res) => {
        _fnSuccess(res, resolved, rejected)
      },
      fail: (res) => {
        _fnFail(res, rejected)
      }
    }

    wx.request(optionsObj)
  })
}

const upload = (filename, filePath) => {
  return new Promise((resolved, rejected) => {
    cos.postObject({
      Bucket: 'beamuse-1301730110',
      Region: 'ap-shanghai',
      Key: '/bill/' + filename,
      FilePath: filePath,
      onProgress: (info) => {
          console.log('success', JSON.stringify(info));
      }
    }, (err, data) => {
        if(!err && data.statusCode === 200) {
          resolved(data)
        } else {
          rejected('上传错误, 请重试')
        }
    });
  })
}

export default {
  get: get,
  post: request,
  delete: remove,
  upload: upload
}